package com.zy.explore.license.interfaces.assembler;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zy.explore.license.domain.mybatis.entity.CustomerLicenseInfo;
import com.zy.explore.license.infrastructure.license.LicenseCheckModel;
import com.zy.explore.license.infrastructure.util.DataBeanUtil;
import com.zy.explore.license.infrastructure.util.FNV;
import com.zy.explore.license.interfaces.frm.CommonIdFrm;
import com.zy.explore.license.interfaces.frm.CommonIdsFrm;
import com.zy.explore.license.interfaces.frm.CustomerLicenseInfoQueryFrm;
import com.zy.explore.license.interfaces.frm.CustomerLicenseInfoSaveFrm;
import com.zy.explore.license.interfaces.validator.CustomerLicenseInfoValidator;
import com.zy.explore.license.interfaces.vo.CustomerLicenseInfoVO;
import com.zy.explore.license.interfaces.vo.PageVO;
import com.google.common.collect.Lists;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * description 表(customer_license_info)对应mybatis-plus的Assembler
 *
 * @author 🇨🇳中国印🇨🇳
 * @date 2022年04月06日 10:13:39
 */
@Component
public class CustomerLicenseInfoAssembler {

    /**
     * 新增数据
     *
     * @param frm 参数对象
     * @return 视图对象
     */
    public CustomerLicenseInfoVO insert(CustomerLicenseInfoSaveFrm frm) {
        CustomerLicenseInfo entity = this.convertFromFrm(frm);
        entity.setId(FNV.pkID(new Date().toString()).toString());
        if (frm.getJsonFormat() == null || !frm.getJsonFormat()) {
            LicenseCheckModel model = LicenseCheckModel.builder().build();
            String macAddress = frm.getMacAddress();
            String cpuSerial = frm.getCpuSerial();
            String mainBoardSerial = frm.getMainBoardSerial();
            if (!StringUtils.isEmpty(macAddress)) {
                if (macAddress.contains(",") || macAddress.contains("，")) {
                    macAddress = macAddress.replace("，", ",");
                    model.setMacAddress(Arrays.asList(macAddress.split(",")));
                } else {
                    model.setMacAddress(Collections.singletonList(macAddress));
                }
            }
            if (!StringUtils.isEmpty(cpuSerial)) {
                model.setCpuSerial(cpuSerial);
            }
            if (!StringUtils.isEmpty(mainBoardSerial)) {
                model.setMainBoardSerial(mainBoardSerial);
            }
            entity.setLicenseCheckModel(JSON.toJSONString(model));
        }
        return convertToVO(entity.save());
    }

    /**
     * 删除对象
     *
     * @param frm 参数对象
     * @return true:删除成功 false:删除失败
     */
    public Integer delete(CommonIdFrm frm) {
        return CustomerLicenseInfo.builder().id(frm.getId()).build().remove();
    }

    /**
     * 更新对象
     *
     * @param frm 待更新的Frm对象
     * @return 成功返回更新后的VO对象，失败返回null
     */
    public CustomerLicenseInfoVO update(CustomerLicenseInfoSaveFrm frm) {
        return convertToVO(convertFromFrm(frm).updateSelective());
    }

    /**
     * 根据ID查询数据
     *
     * @param frm 主键Frm对象
     * @return 成功返回对应ID的VO对象，失败返回null
     */
    public CustomerLicenseInfoVO findById(CommonIdFrm frm) {
        return convertToVO(CustomerLicenseInfo.builder().id(frm.getId()).build().findById());
    }

    /**
     * 通过主键批量查询数据集合
     *
     * @param frm 主键集合Frm对象
     * @return 成功返回对应ID集合的VO对象集合，失败返回空集合
     */
     public List<CustomerLicenseInfoVO> findByIds(CommonIdsFrm frm) {
        List<CustomerLicenseInfoVO> retList = new ArrayList<>();
        if (CollectionUtils.isEmpty(frm.getIds())) {
            return retList;
        }
        List<CustomerLicenseInfo> list = CustomerLicenseInfo.builder().build().findByIds(frm.getIds());
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(x -> retList.add(convertToVO(x)));
        }
        return retList;
     }

    /**
     * 根据条件查询数据集合
     *
     * @param frm 查询条件对象
     * @return 满足条件的数据集合
     */
    public List<CustomerLicenseInfoVO> findList(CustomerLicenseInfoQueryFrm frm) {
        List<CustomerLicenseInfoVO> retList = new ArrayList<>();
        // 查询条件 TODO 请按实际需求设置条件
        QueryWrapper<CustomerLicenseInfo> wrapper = CustomerLicenseInfo.getWrapper(frm);
        // 设置排序 TODO 请安实际需求设置排序
        CustomerLicenseInfo.setSortCriteria(frm.getSortFields(), wrapper, null, null);
        List<CustomerLicenseInfo> list = CustomerLicenseInfo.builder().build().findList(wrapper);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(x -> retList.add(convertToVO(x)));
            return retList;
        }
        return retList;
    }

    /**
     * 根据条件查询分页
     *
     * @param frm 查询条件
     * @return 满足条件的分页
     */
    public PageVO<CustomerLicenseInfoVO> findPage(CustomerLicenseInfoQueryFrm frm) {
        // 设置条件
        QueryWrapper<CustomerLicenseInfo> wrapper = CustomerLicenseInfo.getWrapper(frm);
        // 设置排序
        CustomerLicenseInfo.setSortCriteria(frm.getSortFields(), wrapper, "create_time", false);
        // 分页参数
        int pageNum = frm.getPageNum();
        int pageSize = frm.getPageSize();
        int total = 0;
        PageImpl<?> pageImpl = new PageImpl<>(Lists.newArrayList(), PageRequest.of(pageNum - 1, pageSize), total);
        // 查询分页
        Page<CustomerLicenseInfo> pageInfo = CustomerLicenseInfo.builder().build().findPageInfo(pageImpl, wrapper);
        // 转成PageVO
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize);
        List<CustomerLicenseInfoVO> retList = new ArrayList<>();
        Page<CustomerLicenseInfoVO> retPage = new PageImpl<>(retList, pageRequest, 0L);
        if (pageInfo == null || CollectionUtils.isEmpty(pageInfo.getContent())) {
            return new PageVO<>(retPage);
        }
        pageInfo.getContent().forEach(x -> {
            CustomerLicenseInfoVO vo = convertToVO(x);
            String licenseCheckModelStr = vo.getLicenseCheckModel();
            if (!StringUtils.isEmpty(licenseCheckModelStr)) {
                LicenseCheckModel model = JSON.parseObject(licenseCheckModelStr, LicenseCheckModel.class);
                vo.setCpuSerial(model.getCpuSerial());
                vo.setMainBoardSerial(model.getMainBoardSerial());
                List<String> macAddress = model.getMacAddress();
                if (!CollectionUtils.isEmpty(macAddress) && macAddress.size() > 1) {
                    vo.setMacAddress(String.join(",", macAddress));
                } else {
                    vo.setMacAddress(macAddress.get(0));
                }
                vo.setJsonFormat(false);
            }
            retList.add(vo);
        });
        retPage = new PageImpl<>(retList, pageRequest, pageInfo.getTotalElements());
        return new PageVO<>(retPage);
    }

    /**
     * Frm 转 实体类
     *
     * @param frm 参数对象
     * @return 返回转换后的实体对象
     */
    public CustomerLicenseInfo convertFromFrm(CustomerLicenseInfoSaveFrm frm) {
        // 新增或修改时根据实际业务做参数校验
        CustomerLicenseInfoValidator.validateFrm(this, frm);
        return DataBeanUtil.copyOf(frm, CustomerLicenseInfo.class, true);
    }

    /**
     * 实体类 转 VO
     *
     * @param entity 实体类对象
     * @return 返回转化后的VO对象
     */
    public CustomerLicenseInfoVO convertToVO(CustomerLicenseInfo entity) {
        return entity == null ? null : DataBeanUtil.copyOf(entity, CustomerLicenseInfoVO.class, true);
    }
}
